

import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';

interface UserProfile {
  nickname: string;
  gender: 'male' | 'female' | 'other';
  age: string;
  height: string;
  weight: string;
}

const UserProfilePage: React.FC = () => {
  const navigate = useNavigate();
  const avatarFileInputRef = useRef<HTMLInputElement>(null);
  
  const [userProfile, setUserProfile] = useState<UserProfile>({
    nickname: '张三',
    gender: 'male',
    age: '28',
    height: '175',
    weight: '70'
  });
  
  const [avatarPreview, setAvatarPreview] = useState('https://s.coze.cn/image/LLo9aaymCac/');
  const [showAvatarOverlay, setShowAvatarOverlay] = useState(false);
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);
  const [searchValue, setSearchValue] = useState('');

  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 个人资料';
    return () => { document.title = originalTitle; };
  }, []);

  const handleSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      navigate('/food-search');
    }
  };

  const handleAvatarUploadClick = () => {
    avatarFileInputRef.current?.click();
  };

  const handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        setAvatarPreview(result);
        setShowAvatarOverlay(false);
        console.log('头像已更新（在实际应用中，这里会上传到服务器）');
      };
      reader.readAsDataURL(file);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setUserProfile(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!userProfile.nickname.trim()) {
      alert('请输入昵称');
      return;
    }

    setShowSuccessMessage(true);
    
    setTimeout(() => {
      setShowSuccessMessage(false);
    }, 3000);

    console.log('个人资料已保存:', userProfile);
  };

  const handleCancelClick = () => {
    navigate('/settings');
  };

  const handleNotificationClick = () => {
    console.log('通知按钮点击');
  };

  const handleUserMenuClick = () => {
    console.log('用户菜单点击');
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 bg-white border-b border-border-light h-16 z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
              <i className="fas fa-utensils text-white text-sm"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">食算</h1>
          </div>
          
          {/* 全局搜索框 */}
          <div className="flex-1 max-w-md mx-8">
            <div className="relative">
              <input 
                type="text" 
                placeholder="搜索食物..." 
                value={searchValue}
                onChange={(e) => setSearchValue(e.target.value)}
                onKeyPress={handleSearchKeyPress}
                className="w-full pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
            </div>
          </div>
          
          {/* 右侧操作区 */}
          <div className="flex items-center space-x-4">
            {/* 消息通知 */}
            <button 
              onClick={handleNotificationClick}
              className="relative p-2 text-text-secondary hover:text-primary"
            >
              <i className="fas fa-bell text-lg"></i>
              <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
            </button>
            
            {/* 用户头像和下拉菜单 */}
            <div className="relative">
              <button 
                onClick={handleUserMenuClick}
                className="flex items-center space-x-2 p-1 rounded-lg hover:bg-gray-100"
              >
                <img 
                  src="https://s.coze.cn/image/fY6gq0vSunU/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                />
                <span className="text-sm text-text-primary">张三</span>
                <i className="fas fa-chevron-down text-xs text-text-secondary"></i>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* 左侧菜单 */}
      <aside className={`fixed left-0 top-16 bottom-0 w-60 bg-white border-r border-border-light z-40 ${styles.sidebarTransition}`}>
        <nav className="p-4">
          <ul className="space-y-2">
            <li>
              <Link to="/home" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-home text-lg"></i>
                <span className="font-medium">首页</span>
              </Link>
            </li>
            <li>
              <Link to="/food-search" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-search text-lg"></i>
                <span className="font-medium">食物搜索</span>
              </Link>
            </li>
            <li>
              <Link to="/record-list" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-list text-lg"></i>
                <span className="font-medium">饮食记录</span>
              </Link>
            </li>
            <li>
              <Link to="/history" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-history text-lg"></i>
                <span className="font-medium">历史记录</span>
              </Link>
            </li>
            <li>
              <Link to="/settings" className={`${styles.navItem} ${styles.navItemActive} flex items-center space-x-3 px-4 py-3 rounded-lg`}>
                <i className="fas fa-cog text-lg"></i>
                <span className="font-medium">设置</span>
              </Link>
            </li>
          </ul>
        </nav>
      </aside>

      {/* 主内容区 */}
      <main className="ml-60 mt-16 p-6 min-h-screen">
        {/* 页面头部 */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h2 className="text-2xl font-bold text-text-primary">个人资料</h2>
            <nav className="flex items-center space-x-2 text-sm text-text-secondary mt-1">
              <Link to="/settings" className="hover:text-primary">设置</Link>
              <i className="fas fa-chevron-right text-xs"></i>
              <span>个人资料</span>
            </nav>
          </div>
        </div>

        {/* 保存成功提示 */}
        {showSuccessMessage && (
          <div className={`bg-secondary bg-opacity-10 border border-secondary border-opacity-20 text-secondary px-4 py-3 rounded-lg mb-6 ${styles.saveSuccess}`}>
            <div className="flex items-center space-x-2">
              <i className="fas fa-check-circle"></i>
              <span>个人信息保存成功！</span>
            </div>
          </div>
        )}

        {/* 个人资料表单 */}
        <div className="bg-white rounded-2xl shadow-card p-8">
          <form onSubmit={handleFormSubmit} className="space-y-8">
            {/* 头像上传区域 */}
            <div className="flex flex-col items-center">
              <div className="relative mb-4">
                <div 
                  className={`${styles.avatarUpload} w-24 h-24 rounded-full bg-gray-100 flex items-center justify-center border-2 border-dashed border-gray-300 hover:border-primary transition-colors`}
                  onClick={handleAvatarUploadClick}
                  onMouseEnter={() => setShowAvatarOverlay(true)}
                  onMouseLeave={() => setShowAvatarOverlay(false)}
                >
                  <img 
                    src={avatarPreview}
                    alt="用户头像" 
                    className="w-full h-full rounded-full object-cover"
                  />
                  {showAvatarOverlay && (
                    <div className="absolute inset-0 bg-black bg-opacity-50 rounded-full flex items-center justify-center">
                      <i className="fas fa-camera text-white text-xl"></i>
                    </div>
                  )}
                </div>
                <button 
                  type="button" 
                  onClick={(e) => {
                    e.stopPropagation();
                    handleAvatarUploadClick();
                  }}
                  className="absolute -bottom-1 -right-1 w-8 h-8 bg-primary text-white rounded-full flex items-center justify-center hover:bg-indigo-600 transition-colors"
                >
                  <i className="fas fa-edit text-sm"></i>
                </button>
              </div>
              <p className="text-sm text-text-secondary text-center">点击头像或编辑按钮上传新头像</p>
              <input 
                type="file" 
                ref={avatarFileInputRef}
                accept="image/*" 
                onChange={handleAvatarFileChange}
                className="hidden"
              />
            </div>

            {/* 个人信息表单 */}
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-text-primary border-b border-border-light pb-2">基本信息</h3>
              
              {/* 昵称 */}
              <div className="space-y-2">
                <label htmlFor="nickname" className="block text-sm font-medium text-text-primary">昵称 *</label>
                <input 
                  type="text" 
                  id="nickname" 
                  name="nickname" 
                  value={userProfile.nickname}
                  onChange={handleInputChange}
                  className={`w-full px-4 py-3 border border-border-light rounded-lg ${styles.formInputFocus}`}
                  required
                />
              </div>

              {/* 性别 */}
              <div className="space-y-2">
                <label className="block text-sm font-medium text-text-primary">性别</label>
                <div className="flex space-x-4">
                  <label className="flex items-center space-x-2 cursor-pointer">
                    <input 
                      type="radio" 
                      name="gender" 
                      value="male" 
                      checked={userProfile.gender === 'male'}
                      onChange={handleInputChange}
                      className="text-primary focus:ring-primary" 
                    />
                    <span className="text-text-secondary">男</span>
                  </label>
                  <label className="flex items-center space-x-2 cursor-pointer">
                    <input 
                      type="radio" 
                      name="gender" 
                      value="female" 
                      checked={userProfile.gender === 'female'}
                      onChange={handleInputChange}
                      className="text-primary focus:ring-primary"
                    />
                    <span className="text-text-secondary">女</span>
                  </label>
                  <label className="flex items-center space-x-2 cursor-pointer">
                    <input 
                      type="radio" 
                      name="gender" 
                      value="other" 
                      checked={userProfile.gender === 'other'}
                      onChange={handleInputChange}
                      className="text-primary focus:ring-primary"
                    />
                    <span className="text-text-secondary">其他</span>
                  </label>
                </div>
              </div>

              {/* 年龄 */}
              <div className="space-y-2">
                <label htmlFor="age" className="block text-sm font-medium text-text-primary">年龄</label>
                <input 
                  type="number" 
                  id="age" 
                  name="age" 
                  min="1" 
                  max="120"
                  value={userProfile.age}
                  onChange={handleInputChange}
                  className={`w-full px-4 py-3 border border-border-light rounded-lg ${styles.formInputFocus}`}
                />
              </div>

              {/* 身高 */}
              <div className="space-y-2">
                <label htmlFor="height" className="block text-sm font-medium text-text-primary">身高</label>
                <div className="relative">
                  <input 
                    type="number" 
                    id="height" 
                    name="height" 
                    min="100" 
                    max="250" 
                    step="0.1"
                    value={userProfile.height}
                    onChange={handleInputChange}
                    className={`w-full px-4 py-3 pr-12 border border-border-light rounded-lg ${styles.formInputFocus}`}
                  />
                  <span className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary">cm</span>
                </div>
              </div>

              {/* 体重 */}
              <div className="space-y-2">
                <label htmlFor="weight" className="block text-sm font-medium text-text-primary">体重</label>
                <div className="relative">
                  <input 
                    type="number" 
                    id="weight" 
                    name="weight" 
                    min="30" 
                    max="200" 
                    step="0.1"
                    value={userProfile.weight}
                    onChange={handleInputChange}
                    className={`w-full px-4 py-3 pr-12 border border-border-light rounded-lg ${styles.formInputFocus}`}
                  />
                  <span className="absolute right-4 top-1/2 transform -translate-y-1/2 text-text-secondary">kg</span>
                </div>
              </div>
            </div>

            {/* 操作按钮区 */}
            <div className="flex items-center justify-end space-x-4 pt-6 border-t border-border-light">
              <button 
                type="button" 
                onClick={handleCancelClick}
                className="px-6 py-3 border border-border-light text-text-secondary rounded-lg hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button 
                type="submit" 
                className="px-6 py-3 bg-primary text-white rounded-lg hover:bg-indigo-600 transition-colors"
              >
                保存
              </button>
            </div>
          </form>
        </div>
      </main>
    </div>
  );
};

export default UserProfilePage;

